import os
import ast
import sys
import subprocess
import importlib.util

import stdlib_list


# 判断是否是标准库
def is_stdlib(module_name):
    version_str = f"{sys.version_info.major}.{sys.version_info.minor}"
    stdlib = stdlib_list.stdlib_list(version_str)
    return module_name in stdlib
# 获取 pip 中安装的库的版本
def get_installed_version(module_name):
    try:
        output = subprocess.check_output(
            [sys.executable, "-m", "pip", "show", module_name],
            universal_newlines=True,
            stderr=subprocess.DEVNULL  # 静音 stderr（抑制警告）
        )
        for line in output.splitlines():
            if line.startswith("Version:"):
                return line.split(":", 1)[1].strip()
        return "Unknown"
    except subprocess.CalledProcessError:
        return None

# 扫描代码中 import 的模块
def find_imported_modules(project_dir):
    imported_modules = set()

    for root, _, files in os.walk(project_dir):
        for file in files:
            if file.endswith(".py"):
                full_path = os.path.join(root, file)
                try:
                    with open(full_path, "r", encoding="utf-8") as f:
                        tree = ast.parse(f.read(), filename=file)
                        for node in ast.walk(tree):
                            if isinstance(node, ast.Import):
                                for alias in node.names:
                                    imported_modules.add(alias.name.split('.')[0])
                            elif isinstance(node, ast.ImportFrom):
                                if node.module:
                                    imported_modules.add(node.module.split('.')[0])
                except Exception as e:
                    print(f"解析失败：{full_path}，错误：{e}")
    return sorted(imported_modules)

# 分类模块
def classify_modules(modules):
    stdlib = []
    third_party = []
    local = []

    for mod in modules:
        if is_stdlib(mod):
            stdlib.append(mod)
        else:
            spec = importlib.util.find_spec(mod)
            if spec is None or 'site-packages' not in (spec.origin or ''):
                local.append(mod)
            else:
                third_party.append(mod)

    return stdlib, third_party, local

# 主程序
if __name__ == "__main__":
    project_dir = r"E:\Projects\PythonProject\EMS-RLSim\app"
    all_modules = find_imported_modules(project_dir)
    stdlib, third_party, local = classify_modules(all_modules)

    print("✅ 标准库:")
    for mod in stdlib:
        print(f"  - {mod}")

    print("\n📦 第三方库及版本:")
    for mod in third_party:
        version = get_installed_version(mod)
        print(f"{mod}=={version if version else '未安装'}")

    print("\n📁 本地模块:")
    for mod in local:
        print(f"  - {mod}")
